package com.learn.elasticsearchnews.controller;

import com.learn.elasticsearchnews.model.NewsModel;
import com.learn.elasticsearchnews.service.MySearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

@Slf4j
@Controller
public class SearchController {

	@Autowired
	private MySearchService mySearchService;

	@RequestMapping("/")
	public ModelAndView index() {
		return new ModelAndView("index.html");
	}

	/**
	 * @return 页面调试
	 */
	@RequestMapping("/result")
	public ModelAndView result() {
		return new ModelAndView("result.html");
	}

	/**
	 * @param keywords
	 * @return 搜索数据调试
	 */
	@RequestMapping("/search-list")
	@ResponseBody
	public ArrayList<NewsModel> searchFileList(String keywords, @Nullable Integer from, @Nullable Integer size) {
		ArrayList<NewsModel> hitsList = null;
		try {
			hitsList = mySearchService.searchSinaNews(keywords, from, size);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("共搜到：" + hitsList.size() + " 条数据！");
		return hitsList;
	}

	/**
	 * @param keywords
	 * @return 搜索结果页面
	 */
	@RequestMapping("/search")
	public ModelAndView searchFile(String keywords, @Nullable Integer from, @Nullable Integer size) {
		ArrayList<NewsModel> hitsList = null;
		try {
			hitsList = mySearchService.searchSinaNews(keywords, from, size);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info(keywords + "：共搜到：" + hitsList.size() + " 条数据！");

		ModelAndView mv = new ModelAndView("result.html");
		mv.addObject("keywords", keywords);
		mv.addObject("resultList", hitsList);
		return mv;
	}

}
